package cn.poco.pepsi.util;

import java.io.File;
import java.io.FileOutputStream;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;

public class ImageCompress {

	public static void compress(Context context, File fileDir, Bitmap bmpOrg, String fileName, int imageQuelity)
			throws Exception {
		int width = bmpOrg.getWidth();
		int height = bmpOrg.getHeight();
		float hw = ((float) width) / height;
		int newWidth = 0;
		int newheight = 0;
		if (width > height) {
			newWidth = 500;
			newheight = (int) (newWidth / hw);
		} else {
			newheight = 500;
			newWidth = (int) (newheight * hw);
		}
		float sw = ((float) newWidth) / width;
		float sh = ((float) newheight) / height;
		Matrix matrix = new Matrix();
		matrix.postScale(sw, sh);
		Bitmap resizeBitmap = Bitmap.createBitmap(bmpOrg, 0, 0, width, height, matrix, true);

		File file = new File(fileDir, fileName);
		resizeBitmap.compress(Bitmap.CompressFormat.JPEG, imageQuelity, new FileOutputStream(file));
	}

	public static Bitmap getCompressBmp(Bitmap bmpOrg, int requestWidth) {
		if (bmpOrg != null) {
			int width = bmpOrg.getWidth();
			int height = bmpOrg.getHeight();
			if (width != requestWidth) {
				float hw = ((float) width) / height;
				int newWidth = requestWidth;
				int newheight = (int) (newWidth / hw);
				float sw = ((float) newWidth) / width;
				float sh = ((float) newheight) / height;
				Matrix matrix = new Matrix();
				matrix.postScale(sw, sh);
				Bitmap resizeBitmap = Bitmap.createBitmap(bmpOrg, 0, 0, width, height, matrix, true);
				if (!bmpOrg.isRecycled()) {
					bmpOrg.recycle();
					bmpOrg = null;
				}
				return resizeBitmap;
			}
			return bmpOrg;
		}
		return null;
	}
}
